package cn.kent.simple;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * 141. 环形链表
 * 判断一个链表中是否有环
 */
public class HasCycle {

    /**
     * 双指针，一快一慢，快的每次移动两步，慢的每次移动一步，如果有环，那么快慢指针一定会相遇
     * 0ms
     */
    public static boolean hasCycle3(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next ==null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }

    /**
     * 哈希表
     * 3ms
     */
    public static boolean hasCycle2(ListNode head) {
        Set<ListNode> set = new HashSet<>();
        while (head != null) {
            if (!set.add(head)) {
                return true;
            }
            head = head.next;
        }
        return false;
    }

    /**
     * list
     * 性能很差  >< 385ms
     */
    public static boolean hasCycle(ListNode head) {
        ArrayList<ListNode> nList = new ArrayList<>();
        while (head != null) {
            if (nList.contains(head)) {
                return true;
            }
            nList.add(head);
            head = head.next;
        }
        return false;
    }

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
